package cn.myspringboot.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.myspringboot.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


//全局异常捕获
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    // 捕捉Exception异常，返回统一的错误提示
    @ExceptionHandler(value = Exception.class)
    public JSONResult exceptionErrorMethod(Exception e, HttpServletRequest request) {
        e.printStackTrace();
        log.error("发生异常错误，请求地址：{}，异常信息{}", request.getRequestURI(), e.getMessage());
        return JSONResult.error("服务器内部异常，请联系管理员");
    }

    // 捕捉GlobalException异常，把错误日志抛给用户
    @ExceptionHandler(value = GlobalException.class)
    public JSONResult globalCustomMethod(GlobalException e, HttpServletRequest request) {
        e.printStackTrace();
        log.error("发生异常错误，请求地址：{}，异常信息：{}", request.getRequestURI(), e.getMessage());
        return JSONResult.error(e.getMessage());
    }

    // 捕捉GlobalException异常，把错误日志抛给用户
    @ExceptionHandler(value = NotLoginException.class)
    public JSONResult globalCustomMethod(NotLoginException e, HttpServletRequest request) {
        e.printStackTrace();
        return JSONResult.error("请登录！！！！！！");
    }

    /**
     * 拦截异常 : 这个注解就可以拦截器 MethodArgumentNotValidException 异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult globleException(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> collect = allErrors.stream().map(ObjectError::getDefaultMessage ).collect(Collectors.toList());
        return JSONResult.error("参数校验失败："+String.join(",",collect));
    }
}

